package com.yourname.xhs.util;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import static jdk.jfr.internal.EventWriterKey.getKey;

public class DES {
    public static void main(String[] args) throws Exception {
        String password = "666";
        String originKey = "12345678";

        String cipherText = desEncript(password,originKey);//加密
        System.out.println(cipherText);

        String cleartext2=desDecript("LDiFUdf0iew=",originKey);//解密
        System.out.println(cleartext2);
    }
   //解密
    public static String desDecript(String cipherText, String originKey) throws Exception {
       Cipher cipher=Cipher.getInstance("DES");
       Key key=getKey(originKey);
       cipher.init(Cipher.DECRYPT_MODE,key);
       byte[] decode=Base64.getDecoder().decode(cipherText);
       byte[] doFincal=cipher.doFinal(decode);
       return new String(doFincal);
    }

    //加密是通过对bite进行数学运算
    public static String desEncript(String clearText, String originKey) throws NoSuchPaddingException, NoSuchAlgorithmException,InvalidKeyException,BadPaddingException,IllegalBlockSizeException{
        Cipher cipher=Cipher.getInstance("DES");//获取工具类
        SecretKeySpec key=getKey(originKey);
        cipher.init(Cipher.ENCRYPT_MODE,key);

        //mode:加密解密模式
        //key 对原始秘钥加密后的秘钥

        //加密密文
     byte[] doFinal= cipher.doFinal(clearText.getBytes());
     //new String(doFinal);

        String encoded=Base64.getEncoder().encodeToString(doFinal);
        return encoded;
    }
    private static SecretKeySpec getKey(String originKey){
        byte [] buffer=new byte[8];
        byte[] originBytes=originKey.getBytes();
        for(int i=0;i<8&&i< originBytes.length;i++){
            buffer[i]=originBytes[i];
        }
        SecretKeySpec key=new  SecretKeySpec(buffer,"DES");
        return key;
    }
}